package com.ld.hpfs.web.controller;


import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.RsaDecrypt;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.UserRightsService;
import com.ld.hpfs.web.interseptor.WebConstants;
import com.ld.hpfs.service.HistoryService;

@Controller
public class UserRightsController {
	private static final Logger logger = LoggerFactory.getLogger(UserRightsController.class);

	@Autowired
	private UserRightsService userRightsService;
	
	//用于添加history表
	@Autowired
	private HistoryService historyService;
	
	
	/**
	 * 获取用户权限信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getUserRightsList")
	public void getUserRightsList(ExtPager page,HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		HashMap<String,Object> param = new HashMap<String,Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		String fieldName = "";
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String,Object> orderBy = new HashMap<String,Object>();
			orderBy.put("loginName", "USER_NAME");
			orderBy.put("userName", "FULL_NAME");						
			orderBy.put("email", "E_MAIL");
			orderBy.put("state", "STATE");
		try {
			ArrayList<Map<String,String>> field = page.getSortField();
			StringBuffer sort = new StringBuffer("");
		 	User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			 if(user !=null){
				param.put("pageEnd",page.getStart() + page.getLimit());
				if(field!=null && field.size()>0){
					for(Map<String, String> map : field){
						if(map.get("property").equals("loginName")){
							fieldName = "USER_NAME";
						}else if(map.get("property").equals("userName")){
							fieldName = "FULL_NAME";
						}else if(map.get("property").equals("email")){
							fieldName = "E_MAIL";
						}else{
							fieldName = "STATE";
						}
			        	sort.append(fieldName + " " + map.get("direction") + ",");
			        }
					param.put("orderBy", sort.substring(0,sort.length()-1));
				} 
				else {
					param.put("orderBy", " USER_HID");
				}
				param.put("pageStart", page.getStart());				
			 	param.put("user_id", user.getUserId());
			 	param.put("lang", session.getAttribute(WebConstants.CURRENT_LANG).toString());
			ArrayList<HashMap<String,Object>> logs = userRightsService.getUserRightsList(param);
			if(logs!=null&&logs.size()>0){
				result.put("success", true);
				result.put("total", param.get("pageCount"));
				result.put("data", logs);
			} else {
				result.put("success", true);
				result.put("total", param.get("pageCount"));
				result.put("data", "");
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
	 	}else{
		 	writer.print("");
		  }
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	/**
	 * 获得用户所属公司列表
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getCompanyList")
	public void geCompanyList(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<HashMap<String,Object>> result =userRightsService.getCompanyList();			
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 获得用户角色列表
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getRoleList")
	public void geRoleList(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("lang", session.getAttribute(WebConstants.CURRENT_LANG).toString());
			ArrayList<HashMap<String,Object>> result =userRightsService.getRoleList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 获得数据权限树
	 * @param user
	 * @return
	 */
  @RequestMapping(value = "/getPermissionTreeList")
	    public void getPermissionTreeList(ExtPager page, HttpSession session, HttpServletRequest request,
	            HttpServletResponse response, PrintWriter writer) {
	         String userId  = (String)request.getParameter("userId")  == null ? null : (String)request.getParameter("userId");	   
	        response.setContentType("text/plain;charset=UTF-8");
	        HashMap<String, Object> result = new HashMap<String, Object>();
	        try {
	           	 HashMap<String,Object> param = new HashMap<String,Object>();
		         param.put("userId", userId);
	             result.put("success", true);
	             ArrayList<HashMap<String, Object>> logs = userRightsService.getPermissionTreeList(param);
	                if (logs != null && logs.size() > 0) {
	                    result.put("children", logs);
	                } else {
	                    result.put("children", "");
	                }	           
	            String returnMsg = JackJson.fromObjectToJson(result);
	            logger.debug("{}", returnMsg);
	            writer.print(returnMsg);
	        } catch (Exception e) {
	            logger.error("Exception: {}", e);
	        } finally {
	            writer.flush();
	            writer.close();
	        }
	    }
  
  /**
	 * 修改用户权限
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/editUserRights",method = RequestMethod.POST)
	public void editUserRights(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String loginName = (String)request.getParameter("loginName") == null ? null : (String)request.getParameter("loginName");
        String userName  = (String)request.getParameter("userName")  == null ? null : (String)request.getParameter("userName");
		String email     = (String)request.getParameter("email")     == null ? null : (String)request.getParameter("email");
		String companyId = (String)request.getParameter("companyId") == null ? null : (String)request.getParameter("companyId"); 
		String roleItems = (String)request.getParameter("roleItems") == null ? null : (String)request.getParameter("roleItems");
		String password  = (String)request.getParameter("password")  == null ? null : (String)request.getParameter("password");
		String userId    = (String)request.getParameter("userId")    == null ? null : (String)request.getParameter("userId");
		String editName  = (String)request.getParameter("editName");
		HashMap<String,Object> result = new HashMap<String,Object>();
		 HashMap<String,Object> param = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try{
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			if(user!=null){
					    param = new HashMap<String,Object>();
						param.put("loginName", loginName);
					    param.put("creator_id", user.getUserId());
						param.put("userName", userName);
					 	param.put("email", email);
						param.put("companyId", companyId);
						if(password != ""){
					 	param.put("password", password);}
					 	List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
						String[] roleIds = roleItems.split(",");	
						HashMap<String,String> map= new HashMap<String,String>();
						for(int i=0;i<roleIds.length;i++){
							map = new HashMap<String,String>();
							map.put("roleId", roleIds[i]);
							list.add(map);
						}
						param.put("list", list);
						int ret;						
						param.put("userId", userId);
						param.put("editName", editName);
						
						// 用于添加history表
						HashMap<String, Object> hist_param = new HashMap<String, Object>();
						hist_param.put("id", Integer.parseInt(userId));
			    		hist_param.put("update_id", Integer.parseInt(user.getUserId()));
						hist_param.put("update_name", user.getAccount());
						hist_param.put("roles", roleIds);
						historyService.addUserHistory(hist_param, true);
						
						int check = userRightsService.checkUserName(param);
						if(check == 0 ){
							ret = userRightsService.updateUserRights(param); }
						else{
							ret = 1;
						}				
						if(ret == 0){
							result.put("resultcode",0);
						}else if(ret == 1){
							result.put("resultcode",1);
						}else {
							result.put("resultcode",9);
						}				
				}else{
					result.put("resultcode", 9);
				}
			writer.print(JackJson.fromObjectToJson(result));
		}catch (Exception e){
			logger.error("Exception:",e);
		}finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 增加用户权限
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/addUserRights",method = RequestMethod.POST)
	public void addUserRights(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String loginName = (String)request.getParameter("loginName") == null ? null : (String)request.getParameter("loginName");
        String userName  = (String)request.getParameter("userName")  == null ? null : (String)request.getParameter("userName");
		String email     = (String)request.getParameter("email")     == null ? null : (String)request.getParameter("email");
		String companyId = (String)request.getParameter("companyId") == null ? null : (String)request.getParameter("companyId"); 
		String roleItems = (String)request.getParameter("roleItems") == null ? null : (String)request.getParameter("roleItems");
		String password  = (String)request.getParameter("password")  == null ? null : (String)request.getParameter("password");		
		HashMap<String,Object> result = new HashMap<String,Object>();
		 HashMap<String,Object> param = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try{
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			if(user!=null){
					    param = new HashMap<String,Object>();
						param.put("loginName", loginName);
					    param.put("creator_id", user.getUserId());
						param.put("userName", userName);
					 	param.put("email", email);
						param.put("companyId", companyId);						
					 	param.put("password", password);
					 	List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
						String[] roleIds = roleItems.split(",");	
						HashMap<String,String> map= new HashMap<String,String>();
						for(int i=0;i<roleIds.length;i++){
							map = new HashMap<String,String>();
							map.put("roleId", roleIds[i]);
							list.add(map);
						}
						param.put("list", list);
						int ret;						
						int check = userRightsService.checkUserName(param);
						if(check == 0 ){
								ret = userRightsService.insertUserRights(param); }
						else{
							ret = 1;
						}						
						if(ret == 0){
							result.put("resultcode",0);
						}else if(ret == 1){
							result.put("resultcode", 1);
							}
						 else {
							result.put("resultcode",9);
						}
				
				}else{
					result.put("resultcode", 9);
				}
			writer.print(JackJson.fromObjectToJson(result));
		}catch (Exception e){
			logger.error("Exception:",e);
		}finally {
			writer.flush();
			writer.close();
		}
	}
	
  


/**
 * 重置密码
 * @param user
 * @return
 */
@RequestMapping(value = "/rePassword")
public void rePassword(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
	String userId = (String)request.getParameter("userId") == null ? null : (String)request.getParameter("userId");
	String password = (String)request.getParameter("password") == null ? null : (String)request.getParameter("password");
	HashMap<String,Object> result = new HashMap<String,Object>();
	response.setContentType("text/plain;charset=UTF-8");
	try {
		if(!Tools.isEmpty(userId)){
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("userId", userId);
			param.put("password", password);
			int ret = userRightsService.rePassword(param);
			if(ret == 0){
				result.put("resultcode",0);
			}else{
				result.put("resultcode",9);
			}
		}else{
		  result.put("resultcode",9);
		}
		writer.print(JackJson.fromObjectToJson(result));
	} catch (Exception e) {
		logger.error("Exception: ", e);
	} finally {
		writer.flush();
		writer.close();
	}
}

/**
 * 冻结用户
 * @param user
 * @return
 */
@RequestMapping(value = "/freeze")
public void freeze(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
	String userId = (String)request.getParameter("userId") == null ? null : (String)request.getParameter("userId");
	HashMap<String,Object> result = new HashMap<String,Object>();
	response.setContentType("text/plain;charset=UTF-8");
	try {
		if(!Tools.isEmpty(userId)){
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("userId", userId);
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			int ret;
			boolean check = userRightsService.checkUserRole(param);
			if(userId.equals(user.getUserId())){
				ret = 1;
			}else if(check){
				ret = 2;
			}
			else 
			{ 
				ret = userRightsService.freeze(param);
			}
			
			if(ret == 0){
				result.put("resultcode",0);
			}else if(ret ==1){
				result.put("resultcode",1);
			}else if(ret == 2){
				result.put("resultcode",2);
			}
			else{
				result.put("resultcode",9);
			}
		}else{
		  result.put("resultcode",9);
		}
		writer.print(JackJson.fromObjectToJson(result));
	} catch (Exception e) {
		logger.error("Exception: ", e);
	} finally {
		writer.flush();
		writer.close();
	}
}

/**
 * 解冻用户
 * @param user
 * @return
 */
@RequestMapping(value = "/unfreeze")
public void unfreeze(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
	String userId = (String)request.getParameter("userId") == null ? null : (String)request.getParameter("userId");
	HashMap<String,Object> result = new HashMap<String,Object>();
	response.setContentType("text/plain;charset=UTF-8");
	try {
		if(!Tools.isEmpty(userId)){
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("userId", userId);
			int ret = userRightsService.unfreeze(param);
			if(ret == 0){
				result.put("resultcode",0);
			}else{
				result.put("resultcode",9);
			}
		}else{
		  result.put("resultcode",9);
		}
		writer.print(JackJson.fromObjectToJson(result));
	} catch (Exception e) {
		logger.error("Exception: ", e);
	} finally {
		writer.flush();
		writer.close();
	}
}

/**
 * 设置数据权限
 * @param user
 * @return
 */
@RequestMapping(value = "/setPermission")
public void setPermission(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
	String permissionItems = (String)request.getParameter("permissionItems") == null ? null : (String)request.getParameter("permissionItems");
	String userId = (String)request.getParameter("userId") == null ? null : (String)request.getParameter("userId");
	HashMap<String,Object> result = new HashMap<String,Object>();
	 HashMap<String,Object> param = new HashMap<String,Object>();
	response.setContentType("text/plain;charset=UTF-8");
	try{
		User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
		if(user!=null){
			   param = new HashMap<String,Object>();
		       param.put("userId", userId);
	    	   param.put("creator_id", user.getUserId());
			   List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
			   String[] permissionIds = {};
			   if(permissionItems.length() > 0){
				   permissionIds = permissionItems.split(",");
			   }
			   HashMap<String,String> map= new HashMap<String,String>();
					for(int i=0;i<permissionIds.length;i++){
						map = new HashMap<String,String>();
						map.put("permissionId", permissionIds[i]);
						list.add(map);
					}
					param.put("list", list);
					
					// 用于添加history表
					HashMap<String, Object> hist_param = new HashMap<String, Object>();
					hist_param.put("id", Integer.parseInt(userId));
		    		hist_param.put("update_id", Integer.parseInt(user.getUserId()));
					hist_param.put("update_name", user.getAccount());
					hist_param.put("companies", permissionIds);
					historyService.addUserPermissionHistory(hist_param);
					
				    int ret = userRightsService.setPermission(param);
					if(ret == 0){
						result.put("resultcode",0);
					}
					 else {
						result.put("resultcode",9);
					}
		}else{
				result.put("resultcode", 9);
			}
		writer.print(JackJson.fromObjectToJson(result));
	}catch (Exception e){
		logger.error("Exception:",e);
	}finally {
		writer.flush();
		writer.close();
	}
}

@RequestMapping(value = "/CheckUserNumbers")
public void CheckUserNumbers(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
	try{
		RsaDecrypt rsa = new RsaDecrypt();
//		int Sys_User_Numbers = Integer.parseInt(session.getAttribute(WebConstants.MAX_USER_NUMBER).toString());
		int Sys_User_Numbers = Integer.parseInt(rsa.User_Number());
		HashMap<String,Object> param = new HashMap<String,Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		int Now_User_Numbers = Integer.parseInt(userRightsService.getUserCount(param));
		if(Sys_User_Numbers > Now_User_Numbers){
			result.put("resultcode",1);
		}else{
			result.put("resultcode",0);
		}
		writer.print(JackJson.fromObjectToJson(result));
	}catch (Exception e){
		logger.error("Exception:",e);
	}finally{
		writer.flush();
		writer.close();
	}
}

}


